/**
 * 闹钟同步工具类
 * 用于将设备上的闹钟同步到服务器
 */

import { authManager } from '../api/auth-manager';
import api from '../api/index';

export interface AlarmData {
  id?: number; // 服务器闹钟ID，可选
  userId: number;
  deviceId: number;
  name: string;
  hour: number;
  minute: number;
  repeatMode: number;
  isEnabled: boolean;
  bellType: number;
  bellName: string;
  status: number;
}

/**
 * 闹钟同步管理器
 */
export class AlarmSyncManager {
  
  /**
   * 同步单个闹钟到服务器
   */
  static async syncAlarm(alarmData: AlarmData): Promise<boolean> {
    try {
      // 检查登录状态
      if (!authManager.isAuthenticated()) {
        console.log('用户未登录，跳过闹钟同步');
        return false;
      }

      console.log('同步闹钟到服务器:', alarmData);

      // 调用API同步闹钟
      const response = await api.post('/api/alarm/sync', alarmData);
      
      if (response?.data?.code === 0) {
        console.log('闹钟同步成功:', alarmData.name);
        return true;
      } else {
        console.warn('闹钟同步失败:', response?.data?.message);
        return false;
      }

    } catch (error: any) {
      console.error('闹钟同步异常:', error);
      return false;
    }
  }

  /**
   * 批量同步闹钟到服务器
   */
  static async syncAlarms(alarms: AlarmData[]): Promise<boolean> {
    try {
      // 检查登录状态
      if (!authManager.isAuthenticated()) {
        console.log('用户未登录，跳过批量闹钟同步');
        return false;
      }

      if (alarms.length === 0) {
        console.log('没有闹钟需要同步');
        return true;
      }

      console.log(`开始批量同步${alarms.length}个闹钟到服务器`);

      // 调用API批量同步闹钟
      const response = await api.post('/api/alarm/sync/batch', alarms);
      
      if (response?.data?.code === 0) {
        console.log(`批量闹钟同步成功，共${alarms.length}个闹钟`);
        return true;
      } else {
        console.warn('批量闹钟同步失败:', response?.data?.message);
        return false;
      }

    } catch (error: any) {
      console.error('批量闹钟同步异常:', error);
      return false;
    }
  }

  /**
   * 获取用户闹钟列表
   */
  static async getUserAlarms(userId: number): Promise<AlarmData[]> {
    try {
      const response = await api.get(`/api/alarm/user/${userId}`);
      
      if (response?.data?.code === 0) {
        return response.data.data || [];
      } else {
        console.warn('获取用户闹钟列表失败:', response?.data?.message);
        return [];
      }

    } catch (error: any) {
      console.error('获取用户闹钟列表异常:', error);
      return [];
    }
  }

  /**
   * 获取用户设备闹钟列表
   */
  static async getUserDeviceAlarms(userId: number, deviceId: number): Promise<AlarmData[]> {
    try {
      const response = await api.get(`/api/alarm/user/${userId}/device/${deviceId}`);
      
      if (response?.data?.code === 0) {
        return response.data.data || [];
      } else {
        console.warn('获取用户设备闹钟列表失败:', response?.data?.message);
        return [];
      }

    } catch (error: any) {
      console.error('获取用户设备闹钟列表异常:', error);
      return [];
    }
  }

  /**
   * 删除服务器上的闹钟
   */
  static async deleteAlarm(alarmId: number): Promise<boolean> {
    try {
      const response = await api.delete(`/api/alarm/${alarmId}`);
      
      if (response?.data?.code === 0) {
        console.log('服务器闹钟删除成功:', alarmId);
        return true;
      } else {
        console.warn('服务器闹钟删除失败:', response?.data?.message);
        return false;
      }

    } catch (error: any) {
      console.error('删除服务器闹钟异常:', error);
      return false;
    }
  }

  /**
   * 更新闹钟状态
   */
  static async updateAlarmStatus(alarmId: number, status: number): Promise<boolean> {
    try {
      const response = await api.put(`/api/alarm/${alarmId}/status?status=${status}`);
      
      if (response?.data?.code === 0) {
        console.log('闹钟状态更新成功:', alarmId, status);
        return true;
      } else {
        console.warn('闹钟状态更新失败:', response?.data?.message);
        return false;
      }

    } catch (error: any) {
      console.error('更新闹钟状态异常:', error);
      return false;
    }
  }

  /**
   * 将设备闹钟数据转换为服务器闹钟数据
   */
  static convertDeviceAlarmToServerAlarm(
    deviceAlarm: any, 
    userId: number, 
    deviceId: number
  ): AlarmData {
    return {
      userId,
      deviceId,
      name: deviceAlarm.name || '闹钟',
      hour: deviceAlarm.hour || 0,
      minute: deviceAlarm.min || 0,
      repeatMode: deviceAlarm.repeatMode || 0,
      isEnabled: deviceAlarm.open || true,
      bellType: deviceAlarm.bellType || 0,
      bellName: deviceAlarm.bellName || '',
      status: 1
    };
  }

  /**
   * 检查闹钟是否需要同步
   * 比较设备闹钟和服务器闹钟，找出需要同步的闹钟
   */
  static findAlarmsToSync(
    deviceAlarms: any[], 
    serverAlarms: AlarmData[]
  ): { toAdd: AlarmData[], toUpdate: AlarmData[], toDelete: number[] } {
    const toAdd: AlarmData[] = [];
    const toUpdate: AlarmData[] = [];
    const toDelete: number[] = [];

    // 找出需要添加的闹钟（设备上有但服务器上没有的）
    for (const deviceAlarm of deviceAlarms) {
      const exists = serverAlarms.find(serverAlarm => 
        serverAlarm.hour === deviceAlarm.hour && 
        serverAlarm.minute === deviceAlarm.min &&
        serverAlarm.name === deviceAlarm.name
      );
      
      if (!exists) {
        toAdd.push(deviceAlarm);
      }
    }

    // 找出需要删除的闹钟（服务器上有但设备上没有的）
    for (const serverAlarm of serverAlarms) {
      const exists = deviceAlarms.find(deviceAlarm => 
        serverAlarm.hour === deviceAlarm.hour && 
        serverAlarm.minute === deviceAlarm.min &&
        serverAlarm.name === deviceAlarm.name
      );
      
      if (!exists && serverAlarm.id) {
        toDelete.push(serverAlarm.id);
      }
    }

    return { toAdd, toUpdate, toDelete };
  }
} 